package com.stek.panel;

import java.util.ArrayList;

import android.app.ProgressDialog;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ListView;

import com.stek.R;
import com.stek.app.AppActivity;
import com.stek.base.BaseFragment;
import com.stek.db.DBHelper;
import com.stek.model.AppInfo;
import com.stek.model.FloatInfo;
import com.stek.utils.AppUtils;
import com.stek.utils.Broadcast;
import com.stek.utils.CONFIG;
import com.stek.utils.Functions;
import com.stek.utils.Logging;

public class PanelFrament extends BaseFragment implements OnClickListener {
	public static final String MAIN_PANEL = "com.stek.panel.PanelFrament.MAIN_PANEL";
	public static final String SUB_PANEL = "com.stek.panel.PanelFrament.SUB_PANEL";
	public static final String FAV_PANEL = "com.stek.panel.PanelFrament.FAV_PANEL";
	public static final String KEY_TYPE = "com.stek.panel.PanelFrament.KEY_TYPE";
	public static final String KEY_TITLE = "com.stek.panel.PanelFrament.KEY_TITLE";

	private String type;
	private View rootView;

	public PanelFrament() {
		super();
	}

	public static PanelFrament newInstance(String type, String title) {
		PanelFrament frament = new PanelFrament();
		Bundle bundle = new Bundle();
		bundle.putString(KEY_TYPE, type);
		bundle.putString(KEY_TITLE, title);
		frament.setArguments(bundle);
		return frament;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		type = getArguments().getString(KEY_TYPE);
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		rootView = inflater
				.inflate(R.layout.view_float_page1, container, false);

		if (SUB_PANEL.equals(type)) {
			rootView = inflater.inflate(R.layout.view_float_page2, container,
					false);
		} else if (FAV_PANEL.equals(type)) {
			rootView = inflater.inflate(R.layout.view_float_page3, container,
					false);

		}
		return rootView;
	}

	@Override
	public void onResume() {

		if (SUB_PANEL.equals(type)) {
			loadSub(rootView);
		} else if (FAV_PANEL.equals(type)) {
			loadFav(rootView);
		} else {
			loadMain(rootView);
		}
		super.onResume();
	}

	private void loadFav(View rootView) {
		for (int i = 0; i < 9; i++) {
			AppInfo info = DBHelper.getInstance(getActivity()).findFavorite(
					getActivity(), i);
			int id = getResources().getIdentifier("img_favorite" + i, "id",
					getActivity().getPackageName());
			ImageButton fav = (ImageButton) rootView.findViewById(id);
			Logging.log("tag " + fav.getTag());
			if (null == info) {
				fav.setImageResource(R.drawable.btn_add);
			} else {

				Drawable icon = AppUtils.getApplicationIcon(getActivity(),
						info.pgk);
				if (null == icon) {
					DBHelper.getInstance(getActivity()).deleteFavorite(
							getActivity(), i);
				} else {
					fav.setImageDrawable(icon);
				}
			}
			if (i != 4) {
				fav.setOnClickListener(mFavClickListener);
			}
		}
		//
	}

	//
	private void loadMain(View rootView) {
		DBHelper dbHelper = DBHelper.getInstance(getActivity());
		for (int i = 0; i < 9; i++) {
			int id = getResources().getIdentifier("img" + i, "id",
					getActivity().getPackageName());
			ImageButton view = (ImageButton) rootView.findViewById(id);
			FloatInfo info = dbHelper.findMain(getActivity(), i);
			if (info != null) {

				view.setTag(info.tag);
				view.setImageResource(info.resource);
			} else {
				view.setImageResource(R.drawable.btn_add);
			}
			view.setOnClickListener(this);
		}

	}

	//
	//
	//
	private void loadSub(View rootView) {
		DBHelper dbHelper = DBHelper.getInstance(getActivity());
		for (int i = 0; i < 9; i++) {
			int id = getResources().getIdentifier("imgsub" + i, "id",
					getActivity().getPackageName());
			ImageButton view = (ImageButton) rootView.findViewById(id);
			FloatInfo info = dbHelper.findSettings(getActivity(), i);
			if (info != null) {

				view.setTag(info.tag);
				view.setImageResource(info.resource);
			} else {
				view.setImageResource(R.drawable.btn_add);
			}
			view.setOnClickListener(this);
		}

	}

	private OnClickListener mFavClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			String tag = (String) v.getTag();
			int position = Integer.parseInt(tag.replace(
					getString(R.string.tag_favorite), ""));
			Bundle bundle = new Bundle();
			bundle.putBoolean(AppActivity.EXTRA_PICK_APP, true);
			bundle.putInt(AppActivity.EXTRA_APP_POSITION, position);
			AppUtils.launchActivity(getActivity(), AppActivity.class, null,
					bundle, false);

		}
	};

	@Override
	public void onClick(final View view) {
		
		new AsyncTask<Void, Void, ArrayList<FloatInfo>>() {
			private ProgressDialog progressDialog = new ProgressDialog(getActivity());
			@Override
			protected void onPreExecute() {
				progressDialog.setCancelable(false);
				progressDialog.show();
				super.onPreExecute();
			}
			@Override
			protected ArrayList<FloatInfo> doInBackground(Void... params) {
				// TODO Auto-generated method stub
				return Functions
						.getAll(getActivity());
			}
			
			@Override
			protected void onPostExecute(final ArrayList<FloatInfo> result) {
				if (progressDialog != null && progressDialog.isShowing()) {
					progressDialog.dismiss();
				}
				if (result == null) {
					return;
				}
				final DialogFragment dialogFragment = new DialogFragment() {
					@Override
					public View onCreateView(LayoutInflater inflater,
							ViewGroup container, Bundle savedInstanceState) {
						View contentView = inflater.inflate(R.layout.view_add_list,
								container, false);
						final ArrayList<FloatInfo> floatInfos = result;
						ListView lv = (ListView) contentView
								.findViewWithTag(getString(R.string.tag_list));
						PanelApdater apdater = new PanelApdater(getActivity(),
								R.layout.row_panel, floatInfos);
						lv.setAdapter(apdater);
						lv.setOnItemClickListener(new OnItemClickListener() {

							@Override
							public void onItemClick(AdapterView<?> parent, View v,
									int position, long id) {
								String action = null;
								FloatInfo info = floatInfos.get(position);
								int pos = Integer.valueOf(view.getContentDescription()
										.toString());
								info.position = pos;
								if (info.tag.equals(getString(R.string.tag_add))) {
									if (MAIN_PANEL.equals(type)) {
										DBHelper.getInstance(getActivity())
												.deleteMainWithPosition(getActivity(),
														pos);
										action = CONFIG.BROADCAST.ACTION_MAIN_PANEL_CHANGED;
										loadMain(rootView);
									} else if (SUB_PANEL.equals(type)) {
										DBHelper.getInstance(getActivity())
												.deleteSettingsWithPosition(
														getActivity(), pos);
										action = CONFIG.BROADCAST.ACTION_SUB_PANEL_CHANGED;
										loadSub(rootView);
									}
								} else {
									view.setTag(info.tag);
									if (MAIN_PANEL.equals(type)) {
										DBHelper.getInstance(getActivity()).insertMain(
												getActivity(), info);

										action = CONFIG.BROADCAST.ACTION_MAIN_PANEL_CHANGED;
										loadMain(rootView);
									} else if (SUB_PANEL.equals(type)) {
										info.position = Integer.valueOf(view
												.getContentDescription().toString());
										DBHelper.getInstance(getActivity())
												.insertSettings(getActivity(), info);
										action = CONFIG.BROADCAST.ACTION_SUB_PANEL_CHANGED;
										loadSub(rootView);
									}
								}
								Broadcast.sendBroadcast(getActivity(), action);
								dismiss();

							}
						});
						return contentView;

					}

					@Override
					public void onCreate(Bundle savedInstanceState) {
						setStyle(STYLE_NO_TITLE, 0);
						super.onCreate(savedInstanceState);
					}

				};

				dialogFragment.show(getFragmentManager(), "");
				super.onPostExecute(result);
			}
		}.execute();
		

	}

}
